<template>
  <div class="app-container">
    <el-form ref="userForm" :model="userForm" label-width="80px" :rules="updateUserRules">
      <el-form-item
        label="昵称"
        prop="username"
      >
        <el-input v-model="userForm.username" :disabled="true" />
      </el-form-item>
      <el-form-item
        label="手机号码"
        prop="phone"
      >
        <el-input v-model="userForm.phone" />
      </el-form-item>
      <el-form-item
        label="个性签名"
        prop="utograph"
      >
        <el-input v-model="userForm.utograph" />
      </el-form-item>
      <el-form-item label="头像" prop="avatarUrl">
        <upload-img v-model="userForm.avatarUrl" @getUrl="getCover" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updateUserInfoFun('userForm')">确认修改</el-button>
        <el-button @click="prev">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { updateUserInfo } from '@/api/user.js'
import uploadImg from '@/components/Common/uploadImg.vue'
export default {
  components: { uploadImg },
  data() {
    return {
      updateUserRules: {
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          {
            required: true,
            pattern: /^[1][3,4,5,7,8,9][0-9]{9}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ]
      },
      userForm: {
        username: '',
        phone: '',
        avatarUrl: '',
        utograph: '' // 个性签名
      }
    }
  },
  created() {
    // 解构vuex中获取的个人信息
    const { username, phone, utograph, avatarUrl } = this.$store.getters.userInfo
    console.log(this.$store.getters.userInfo)
    // 把个人信息赋值给form
    this.userForm = {
      username,
      phone,
      utograph,
      avatarUrl
    }
    console.log(this.userForm.avatarUrl)
  },
  // 修改个人信息
  methods: {
    updateUserInfoFun(formInfo) {
      this.$refs[formInfo].validate((valid) => {
        if (valid) {
          updateUserInfo(this.form).then(res => {
            console.log('修改成功', res)
            const { code } = res
            if (code === 200) {
              this.$message({
                type: 'success',
                message: '修改成功!'
              })
            }
          }).catch(() => {
            this.$message({
              type: 'warning',
              message: '修改失败!'

            })
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })

      console.log('@@@', this.form)
    },
    // 返回上一个页面
    prev() {
      this.$router.back()
    },
    // 上传头像
    getCover(url) {
      this.userForm.avatarUrl = url
    }
  }
}
</script>

<style lang="scss" scoped>
    .app-container{
      width: 360px;
      margin: 0 auto;
    }
</style>>

